package com.example.reagent_management.ui.operatedialog.dialogs

import android.util.Log
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.example.lib_base.base.BaseDBDialogFragment
import com.example.lib_base.base.DataBindingConfig
import com.example.lib_base.widget.InputTextManager
import com.example.reagent_management.BR
import com.example.reagent_management.R
import com.example.reagent_management.databinding.FragmentInstoreBinding
import com.example.reagent_management.room.entity.ReagentInformation
import com.example.reagent_management.room.entity.ReagentOperate
import com.example.reagent_management.service.works.HistoryWork
import com.example.reagent_management.service.works.WorksBuild
import com.example.reagent_management.service.works.setHistoryData
import com.example.reagent_management.ui.operatedialog.viewmodle.StoreViewModel
import com.hjq.toast.ToastUtils
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import javax.inject.Inject

@AndroidEntryPoint
class InStoreFragment : BaseDBDialogFragment() {
    //试剂信息ID
    private var reagentId = 0L

    //使用by viewModels()来委托可能会有问题 这些初始化都必须主线程初始化
    private val mState: StoreViewModel by viewModels()

    @Inject
    lateinit var works : WorksBuild

    override fun initViewOrObserve() {
        setTransAndHeight(true, 0.5f)
        //可能view实例为空?
        with(getBinding() as FragmentInstoreBinding) {
            InputTextManager.with(lifecycleOwner)
                .addView(reagentNames)
                .addView(batchNumber)
                .addView(days)
                .addView(countss)
                .setMain(ok)
                .build()
            choose.setOnClickListener {
                val storeChooseFragment = StoreChooseFragment()
                storeChooseFragment.show(childFragmentManager, "StoreChooseFragment")
                //拿到弹窗返回的数据
                storeChooseFragment.setOnDataListener { it1 ->
                    if (it1 is ReagentInformation){
                        it1.let {
                            this.reagentNames.text = it.reagentName
                            this.reagentType.text = it.reagentType
                            reagentId = it.reagent_id
                        }
                    }
                }
            }
            //保存
            ok.setOnClickListener {
                no.isClickable = false
                ok.isClickable = false
                val batch = batchNumber.text.toString()
                val supplier = buss.text.toString()
                val days = days.text.toString().toLong()
                val counts = countss.text.toString().toLong()
                lifecycleScope.launch(Dispatchers.IO) {
                    //先查询最后一次入库的总数量
                    Log.e(TAG, "initViewOrObserve: $mState")
                    val lastCounts = mState.getLastCounts(batch, reagentId)?.counts?:0L
                    val allCounts = counts + lastCounts
                    val reagentOperate =
                        ReagentOperate(batch, supplier, days, reagentId, true, allCounts,counts)
                    //需要调用await才开始执行  本来也在IO线程了，其实直接拿结果就行 async和withContent做并发的多
                    val success = async(coroutineContext, CoroutineStart.LAZY) {
                        return@async mState.insertOperate(
                            reagentOperate
                        )
                    }
                    val reagentOperateId = success.await()
                    if (reagentOperateId != -1L) {
                        //历史记录插入应该开后台来插入  使用workManager
                        val data = setHistoryData(
                            arrayOf(reagentNames.text.toString(), batch),
                            longArrayOf(
                                allCounts, reagentId,
                                reagentOperateId,counts
                            ), true
                        )
                        works.Builder().setInputData(data,HistoryWork::class.java).build()
                        ToastUtils.show("入库成功")
                        dismissAllowingStateLoss()
                    } else {
                        mState.insertSuccess.value = false
                        ToastUtils.show("入库失败")
                    }
                    no.isClickable = true
                    ok.isClickable = true
                }
            }
        }
    }

    override fun getDataBindingConfig(): DataBindingConfig? {
        return DataBindingConfig(R.layout.fragment_instore, BR.VM,mState)
            .addBindingParam(BR.clickProxy, ClickProxy())
    }

    inner class ClickProxy {
        fun cancel() {
            this@InStoreFragment.dismissAllowingStateLoss()
        }
    }
}